package com.rongji.egov.fileupload.s3.utils;

import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.nio.file.StandardOpenOption;

@Service
public class S3Util {
    @Resource
    S3FileIdUtils s3FileIdUtils;
    public void upload(String key, byte[] file){
        Path targetFile = s3FileIdUtils.getFilePath(key);
        Path parent = targetFile.getParent();
        try {
            Files.createDirectories(parent);
        } catch (IOException e) {
            throw new RuntimeException("创建目录错误！", e);
        }

        try {
            Files.write(targetFile, file, StandardOpenOption.CREATE_NEW);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public void upload(String key, InputStream is){
        Path targetFile = s3FileIdUtils.getFilePath(key);
        Path parent = targetFile.getParent();
        try {
            Files.createDirectories(parent);
        } catch (IOException e) {
            throw new RuntimeException("创建目录错误！", e);
        }
        try {
            Files.copy(is, targetFile,
                    StandardCopyOption.REPLACE_EXISTING);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        IOUtils.closeQuietly(is);
    }

    public byte[] getFile(String key){
        Path path = s3FileIdUtils.getFilePath(key);
        byte[] bytes;
        try {
            bytes = Files.readAllBytes(path);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return bytes;
    }

    public void deleteFile(String key){
        Path path = s3FileIdUtils.getFilePath(key);
        try {
            if(path.toFile().exists()){
                Files.delete(path);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
